package com.hitqz.robot.biz.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hitqz.robot.api.business.dto.RobotLockPos;
import com.hitqz.robot.api.business.entity.RobotLockPosEntity;
import com.hitqz.robot.biz.mapper.RobotLockPosMapper;
import com.hitqz.robot.biz.service.RobotLockPosService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 机器人管理 服务实现类
 * </p>
 *
 * @author xiaojiezhang
 * @since 2021-12-20
 */
@Service
public class RobotLockPosServiceImpl extends ServiceImpl<RobotLockPosMapper, RobotLockPosEntity> implements RobotLockPosService {

    private final String lock_A=new String("robotLockPos");

    /**
     * @param robotSn
     * @return
     */
    @Override
    public List<RobotLockPosEntity> getByRobotSn(String robotSn) {
        return baseMapper.getByRobotSn(robotSn);
    }

    @Override
    public Integer deleteByRobotSnAndCommpathName(String robotSn, String commonPath) {
        return baseMapper.deleteByRobotSnAndCommonPath(robotSn, commonPath);
    }

    @Override
    public Integer deleteByRobotSn(String robotSn) {
        return baseMapper.deleteByRobotSn(robotSn);
    }

    @Override
    public int deleteNotExist(String commonPathNameF, String commonPathNameS, String commonPathNameT) {
        return baseMapper.deleteNotExist(commonPathNameF, commonPathNameS, commonPathNameT);
    }

    /**
     * 批量保存
     *
     * @param list
     * @return
     */
    @Override
    public Integer batchInsert(String robotSn, String commonPath, List<RobotLockPos> list, Boolean deleteFlag) {
        synchronized (lock_A) {
            try {
                if(deleteFlag){
                    baseMapper.deleteOthers(robotSn);
                }
                List<RobotLockPosEntity> dbLock =  baseMapper.getByRobotSn(robotSn);
                if(dbLock.size()>0) {
                    int tryCount=0;
                    int ret = baseMapper.deleteByRobotSn(robotSn);
                    while(ret <=0 && tryCount<10){
                        Thread.sleep(100);
                        ret = baseMapper.deleteByRobotSn(robotSn);
                        tryCount++;
                    }
                    Thread.sleep(100);
                }
                return baseMapper.batchInsert(list);
            }catch (Exception e){
                return 0;
            }
        }
    }
}
